﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Web.Services;
using Medianamik.Core;
using Medianamik.Core.Logging;
using Medianamik.Globalization;

namespace Medianamik.UI.Services
{
    [WebService(Namespace = "http://absolunet.com/medianamik/webservices/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class ResourcesService : WebService
    {
        private static ILogger _logger;
        protected static ILogger Logger
        {
            get
            {
                return _logger
                    ?? (_logger = new ObjectFactory<ILogger>().Get("ResourcesServiceLogger"));
            }
        }

        [WebMethod]
        public DataTable GetAllNewOrUpdatedResources()
        {
            Logger.Trace("Tentative de mise à jour des ressources.");

            var lastResourcesUpdate = DateTime.MinValue.ToUniversalTime();

            var newOrUpdatedResources = new DataTable();

            try
            {
                var configurations = ConfigManager.GetAllConfigurations();

                if (configurations.ContainsKey(MedianamikConfigurations.LastResourcesUpdateKey))
                    DateTime.TryParse(configurations[MedianamikConfigurations.LastResourcesUpdateKey],
                                      out lastResourcesUpdate);

                var resourceDataManager = new MedianamikResourceDataManager();


                var cultureNames = ConfigManager.GetMedianamikCultures().Select(c => c.CultureName);

                //newOrUpdatedResources = resourceDataManager
                //    .GetNewOrUpdatedResources(cultureNames, 
                //    lastResourcesUpdate);

                Logger.Trace("Récupération des ressources terminée avec succès. (" +
                    newOrUpdatedResources.Rows.Count + ")");
            }
            catch (Exception ex)
            {
                Logger.Error("Erreur lors de la mise à jour des ressources.", ex);
            }

            ConfigManager.SaveConfiguration(MedianamikConfigurations.LastResourcesUpdateKey,
                                            DateTime.Now.ToUniversalTime().ToString());

            return newOrUpdatedResources;
        }

        [WebMethod]
        public void UpdatedAllResources()
        {

        }
    }
}
